//
//  AsNewMsgViewController.m
//  AttendenceSys
//
//  Created by ld on 16/5/30.
//  Copyright © 2016年 窦芳俊. All rights reserved.
//

#import "AsNewMsgViewController.h"

@interface AsNewMsgViewController ()

@end


@implementation AsNewMsgViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _infoArray = [[NSMutableArray alloc] init];
    
    [self initView];
    
    [self fetchTeacherNewMsg];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)initView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[AsNewMsgCell class] forCellReuseIdentifier:NSStringFromClass([AsNewMsgCell class])];
    [self.view addSubview:_tableView];
}

- (void)fetchTeacherNewMsg
{
    //消息接口 http://211.65.216.54/getStudentDutyList.action?userCode=xiaohu&page=1&rowNum=10&userType=1(1表示老师2表示学生)
    
    if (_infoArray == nil)
    {
        _infoArray = [[NSMutableArray alloc] init];
    }
    
    NSString *refer = @"getStudentDutyList.action";
    NSString *prefix = kASHttpUrl(refer);
    NSString *teacherCode = [ASAppDelegate sharedAppDelegate].userInfo.userCode;
    NSString *rowNum = @"10";
    NSString *page = @"1";
    NSString *totalUrl = [NSString stringWithFormat:@"%@?userCode=%@&page=%@&rowNum=%@&userType=1", prefix, teacherCode, page, rowNum];
    
    [SVProgressHUD showWithStatus:@"获取中..." maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    
    typeof(self) __weak weakSelf = self;
    [networkingEngine POST:totalUrl parameters:nil success:^(id responseObject) {
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        if (isSuccessRsp(jsonRsp))
        {
            NSArray* data = [jsonRsp objectForKey:kASJsonData];
            [weakSelf parseTeacherNewMsg:data];
            [SVProgressHUD dismiss];
            
            [_tableView reloadData];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
    } failure:^(NSError *error) {
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}

- (void)parseTeacherNewMsg:(NSArray *)array
{
    for (unsigned int i = 0; i < [array count]; i++)
    {
        ASNewMsgInfo* msgInfo = [[ASNewMsgInfo alloc] init];
        
        msgInfo.actionDesc = [[array objectAtIndex:i] objectForKey:@"actionDesc"];
        msgInfo.actionPicture = [[array objectAtIndex:i] objectForKey:@"actionPicture"];
        msgInfo.courseNumber = [[array objectAtIndex:i] objectForKey:@"courseNumber"];
        msgInfo.imageUrl = [[array objectAtIndex:i] objectForKey:@"imageUrl"];
        msgInfo.leaveDate = [[array objectAtIndex:i] objectForKey:@"leaveDate"];
        msgInfo.pkApproHistoryId = [[array objectAtIndex:i] objectForKey:@"pkApproHistoryId"];
        msgInfo.portraitNum = [[array objectAtIndex:i] objectForKey:@"portraitNum"];
        msgInfo.submitDate = [[array objectAtIndex:i] objectForKey:@"submitDate"];
        msgInfo.userCode = [[array objectAtIndex:i] objectForKey:@"userCode"];
        msgInfo.userName = [[array objectAtIndex:i] objectForKey:@"userName"];
        msgInfo.weekDay = [[array objectAtIndex:i] objectForKey:@"weekDay"];
        msgInfo.approveCode = [[array objectAtIndex:i] objectForKey:@"approveCode"];
        msgInfo.courseId = [[array objectAtIndex:i] objectForKey:@"courseId"];
        msgInfo.courseName = [[array objectAtIndex:i] objectForKey:@"courseName"];
        
        [_infoArray addObject:msgInfo];
    }
}

- (void)updateCellButtonStatus:(ASNewMsgInfo *)msgInfo msgCell:(AsNewMsgCell *)cell
{
    // 设置请假批复按钮状态 // approveCode 1审批通过 2审批不通过 3待审批 4已经撤销
    if ([msgInfo.approveCode isEqualToString:@"1"])
    {
        cell.reviewBtn.hidden = NO;
        cell.reviewBtn.enabled = NO;
        cell.reviewBtn.backgroundColor = RGB(167, 167, 167);
        [cell.reviewBtn setTitle:@"已同意" forState:UIControlStateDisabled];
    }
    else if ([msgInfo.approveCode isEqualToString:@"2"])
    {
        cell.reviewBtn.hidden = NO;
        cell.reviewBtn.enabled = NO;
        cell.reviewBtn.backgroundColor = RGB(167, 167, 167);
        [cell.reviewBtn setTitle:@"不通过" forState:UIControlStateDisabled];
    }
    else if ([msgInfo.approveCode isEqualToString:@"3"])
    {
        cell.reviewBtn.hidden = NO;
    }
    else if ([msgInfo.approveCode isEqualToString:@"4"])
    {
        cell.reviewBtn.hidden = NO;
        cell.reviewBtn.enabled = NO;
        cell.reviewBtn.backgroundColor = RGB(167, 167, 167);
        [cell.reviewBtn setTitle:@"已撤销" forState:UIControlStateDisabled];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_infoArray count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ASNewMsgInfo* msgInfo = [_infoArray objectAtIndex:[indexPath row]];
    
    AsNewMsgCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AsNewMsgCell class])];
    [cell resetCellStatus];
    cell.delegate = self;
    
    // 设置请假批复按钮状态 // approveCode 1审批通过 2审批不通过 3待审批 4已经撤销
    [self updateCellButtonStatus:msgInfo msgCell:cell];
    
    NSString *couseInfo = [NSString stringWithFormat:@" %@   %@ %@", msgInfo.leaveDate, msgInfo.courseName, msgInfo.userName];
    cell.appBegEndTimeLab.text = couseInfo;
    cell.appTimeLab.text = [NSString stringWithFormat:@"申请时间: %@", msgInfo.submitDate];
    //cell.appInfoLab.text = [NSString stringWithFormat:@"第%@节课", msgInfo.courseNumber];
    cell.appInfoLab.text = @"";
    cell.msgDesc.text = msgInfo.actionDesc;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return AsNewMsgCellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - AsNewMsgCellDelegate
- (void)reviewBtnClick:(UITableViewCell *)cell
{
    // 审批接口（老师用） http://211.65.216.54/approveLeave.action?userCode=xiaohu&pKApproHistoryId=1
    
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    ASNewMsgInfo* msgInfo = [_infoArray objectAtIndex:[indexPath row]];
    if (msgInfo)
    {
        NSString *refer = @"approveLeave.action";
        NSString *prefix = kASHttpUrl(refer);
        NSString *teacherCode = [ASAppDelegate sharedAppDelegate].userInfo.userCode;
        NSString *totalUrl = [NSString stringWithFormat:@"%@?userCode=%@&pKApproHistoryId=%@", prefix, teacherCode, msgInfo.pkApproHistoryId];
        
        [SVProgressHUD showWithStatus:@"提交中..." maskType:SVProgressHUDMaskTypeClear];
        ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
        
        typeof(self) __weak weakSelf = self;
        __weak UITableViewCell* bCell = cell;
        [networkingEngine POST:totalUrl parameters:nil success:^(id responseObject) {
            NSDictionary* jsonRsp = (NSDictionary *)responseObject;
            if (isSuccessRsp(jsonRsp))
            {
                //NSArray* data = [jsonRsp objectForKey:kASJsonData];
                [SVProgressHUD dismiss];
                
                [weakSelf approveLeave:bCell];
            }
            else
            {
                [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
            }
        } failure:^(NSError *error) {
            //[SVProgressHUD showErrorWithStatus:error.description];
            [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
        }];
    }
}

- (void)approveLeave:(UITableViewCell *)cell
{
    // 老师同意某一课时假
    //NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    AsNewMsgCell *asCell = (AsNewMsgCell*)cell;
    asCell.reviewBtn.enabled = NO;
    asCell.reviewBtn.backgroundColor = RGB(167, 167, 167);
    [asCell.reviewBtn setTitle:@"已同意" forState:UIControlStateDisabled];
}


@end







